/**
 * 
 */
package x10.eventServices.tcp;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.logging.Logger;

import x10.event.X10Event;
import x10.eventServices.X10EventListener;

/**
 * @author Denny
 *
 */
public class TCPConnectionManager implements X10EventListener, Runnable {
    final String eventListenerName = "TCPConnectionManager";
    Logger logger = Logger.getLogger(this.getClass().getName());
    X10EventListener eventServiceManager;
    ArrayList<TCPConnection> connections = new ArrayList<TCPConnection>();
    TCPConnectionListener connectionListener;
    int port;
    int maxConnections;
    
    public TCPConnectionManager(X10EventListener serviceManager, int port, int maxConnections){
	this.eventServiceManager = serviceManager;
	this.port = port;
	this.maxConnections = maxConnections;

	//Start the TCP connection listener
	connectionListener = new TCPConnectionListener(this, port, maxConnections);
	connectionListener.start();
    }

    public void run(){
    }
    

    /**
     * getEventListenerName() - returns the name of this X10EventListener class
     */
    public String getEventListenerName(){
	return eventListenerName;
    }
    
    public boolean atMaxConnections(){
	if(connections.size() >= maxConnections){
	    return true;
	} else {
	    return false;
	}
    }

    public void closeConnections(){
	logger.fine("Closing all TCP client connections");
	Iterator<TCPConnection> it = connections.iterator();
	while(it.hasNext()){
	    it.next().close();
	}
    }

    public void enqueueTCPConnection(TCPConnection connection){
	connections.add(connection);
    }
    
    public void dequeueTCPConnection(TCPConnection connection){
	if(connections.contains(connection)){
	    connections.remove(connection);
	}
    }
    
    public synchronized void transmitEvent(X10Event event){
	eventServiceManager.receiveEvent(event);
    }

    public synchronized void receiveEvent(X10Event event){
	for(TCPConnection connection: connections){
	    connection.receiveEvent(event);
	}
    }
    

}
